/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/

#include "../memstreambuf.h"
#include <string.h>
#include <assert.h>

using namespace greenhills::util;
using namespace std;

memstreambuf::memstreambuf(unsigned int pInitialSize, unsigned int pIncrement)
:mIncrement(pIncrement), mAllocatedSize(pInitialSize)
{
    mData = new char[mAllocatedSize];
    memset(mData, 0, mAllocatedSize);
    this->setp(mData, mData + mAllocatedSize);
    this->setg(0, 0, 0);
}

memstreambuf::memstreambuf(const char *pData, unsigned int pLength)
:mIncrement(0), mAllocatedSize(pLength)
{
    mData = new char[pLength+50];
    memset(mData, 0, pLength);
    memcpy(mData, pData, pLength);

    this->setg(mData, mData, mData + mAllocatedSize);
    this->setp(0, 0);
}

memstreambuf::~memstreambuf()
{
    delete[] mData;
}

memstreambuf::int_type memstreambuf::overflow(memstreambuf::int_type c)
{
    //resize mData
    int oldAllocatedSize = mAllocatedSize;
    realloc( mAllocatedSize + mIncrement );
    this->setp(mData + oldAllocatedSize, mData + mAllocatedSize);


    if(!traits_type::eq_int_type(c, traits_type::eof())) {
        c = traits_type::to_char_type(c);
    }

    //and write passed byte
    memstreambuf::int_type  rc = sputc(c);

    return traits_type::not_eof(rc);
}

void memstreambuf::realloc( unsigned int pNewSize)
{
    int len = length();

    char *buffer = new char[pNewSize];
    mAllocatedSize = pNewSize;
    memcpy(buffer, mData, len);

    delete[] mData;
    mData = buffer;
}

const char *memstreambuf::data() const
{
    return mData;
}

unsigned int memstreambuf::length() const
{
    return pptr()-mData;
}
